<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar

    class="page-nav-bar"
    title="个人信息"
    left-arrow @click-left="$router.back()" />
    <!-- /导航栏 -->
    <input @change="onChange" type="file" hidden ref="inputFile"/>
    <van-cell title="头像" is-link @click="$refs.inputFile.click()">
      <van-image
        class="avatar"
        fit="cover"
        round
        :src="user.photo"
      />
    </van-cell>
    <van-cell title="昵称" @click="isShowEdit=true" :value="user.name" is-link />
    <van-cell title="性别" @click="isShowEditSex=true" :value="user.gender?'女':'男'" is-link />
    <van-cell title="生日" @click="isShowEditBirth=true" :value="user.birthday" is-link />
    <!-- 编辑姓名弹出层 -->
    <van-popup v-model="isShowEdit" position="bottom"
    :style="{ height: '100%' }" >
      <user-edit v-if="isShowEdit" v-model="user.name" @close="isShowEdit=false"/>
  </van-popup>
  <!-- 编辑性别弹出层 -->
  <van-popup v-model="isShowEditSex" position="bottom">
    <user-sex v-if="isShowEditSex" v-model="user.gender" @close="isShowEditSex=false" />
  </van-popup>
  <!-- 编辑生日弹层 -->
  <van-popup v-model="isShowEditBirth" position="bottom">
    <user-birth v-if="isShowEditBirth" v-model="user.birthday" @close="isShowEditBirth=false"/>
  </van-popup>
  <!-- 编辑头像的弹层 -->
  <van-popup  v-model="isShowEditImage" position="bottom" :style="{ height: '100%' }">
   <user-image @update-photo="user.photo=$event" v-if="isShowEditImage" @close="isShowEditImage=false" :img="imgUrl" />
  </van-popup>
  </div>
</template>
<script>
import { getUserProfile } from '@/api/user.js'
import UserEdit from './components/UserEdit.vue'
import UserSex from './components/UserSex.vue'
import UserBirth from './components/UserBirth.vue'
import UserImage from './components/UserImage.vue'
export default {
  components: { UserEdit, UserSex, UserBirth, UserImage },
  data () {
    return {
      user: {},
      isShowEdit: false,
      isShowEditSex: false,
      isShowEditBirth: false,
      isShowEditImage: false,
      imgUrl: ''
    }
  },

  created () {
    this.loadUserProfile()
  },

  methods: {
    async loadUserProfile () {
      try {
        const res = await getUserProfile()
        this.user = res
      } catch (error) {

      }
    },
    // 选择文件的输入框发生变化后
    // 如果发生变化 显示弹层
    onChange (e) {
      if (e.target.value === '') return
      this.isShowEditImage = true
      // 如果不进行裁剪 e.target.files[0]可以直接传给后端
      this.imgUrl = URL.createObjectURL(e.target.files[0])
      // 将图片值为空
      e.target.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
  /deep/.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
